package controle;

import java.io.IOException;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import modelo.Usuario;
import persistencia.UsuarioRepositorio;

@WebFilter(filterName = "AutenticacaoUsuario", urlPatterns =
{
    "/autenticacao_usuario"
}, dispatcherTypes =
{
    DispatcherType.REQUEST
})
public class AutenticacaoUsuario implements Filter
{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
    {
        HttpServletRequest hr = (HttpServletRequest) request;
        Usuario u = (new UsuarioRepositorio()).encontrarPeloLoginSenha(
                hr.getParameter("login"),
                hr.getParameter("senha"));
        
        hr.getSession(true).setAttribute("usuario", u);

        ((HttpServletResponse) response).sendRedirect("index.jsp");
    }

    @Override
    public void destroy()
    {
    }
}